package com.eric.utils;

import com.alibaba.fastjson.JSONObject;
import com.eric.seo.serp.BaiduSERPAnalyzer2;

/**
 * 格式化输入工具类
 * 
 * @author lizhgb
 * @date 2015-10-14
 *
 */
public final class JsonUtils {

	static String formatedJsonStr;

	public static void main(String args[]) {
		BaiduSERPAnalyzer2 bd = new BaiduSERPAnalyzer2("文具");
		bd.run();
		JSONObject json = (JSONObject) bd.result().get("top10");
		System.out.println(formatJson(json.toJSONString()));
	}

	/**
	 * 格式化
	 * 
	 * @param jsonStr
	 * @return
	 * @author lizhgb
	 * @Date 2015-10-14 下午1:17:35
	 */
	public static String formatJson(String jsonStr) {
		if (null == jsonStr || "".equals(jsonStr))
			return "";
		StringBuilder sb = new StringBuilder();
		char last = '\0';
		char current = '\0';
		int indent = 0;
		for (int i = 0; i < jsonStr.length(); i++) {
			last = current;
			current = jsonStr.charAt(i);
			switch (current) {
			case '{':
			case '[':
				sb.append(current);
				sb.append('\n');
				indent++;
				addIndentBlank(sb, indent);
				break;
			case '}':
			case ']':
				sb.append('\n');
				indent--;
				addIndentBlank(sb, indent);
				sb.append(current);
				break;
			case ',':
				sb.append(current);
				if (last != '\\') {
					sb.append('\n');
					addIndentBlank(sb, indent);
				}
				break;
			default:
				sb.append(current);
			}
		}

		formatedJsonStr = sb.toString().replaceAll("\\\\", "").replace("\"{", "{").replace("}\"", "}");

		return formatedJsonStr;
	}

	/**
	 * 添加space
	 * 
	 * @param sb
	 * @param indent
	 * @author lizhgb
	 * @Date 2015-10-14 上午10:38:04
	 */
	private static void addIndentBlank(StringBuilder sb, int indent) {
		for (int i = 0; i < indent; i++) {
			sb.append('\t');
		}
	}
}
